package com.hengxinguotong.zhihuichengjian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.HomeMenuListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.HomeInfo;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.bean.Message;
import com.hengxinguotong.zhihuichengjian.bean.MessageListRes;
import com.hengxinguotong.zhihuichengjian.bean.VedioMeetingBean;
import com.hengxinguotong.zhihuichengjian.bean.VedioMeetingRst;
import com.hengxinguotong.zhihuichengjian.sys.CaptureActivity;
import com.hengxinguotong.zhihuichengjian.ui.ActivityJumper;
import com.hengxinguotong.zhihuichengjian.ui.MainActivity;
import com.hengxinguotong.zhihuichengjian.ui.MessageActivity;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.utils.ActivityController;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.DateUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.NetworkImageView;
import com.hengxinguotong.zhihuichengjian.widget.view.NoneRollGridView;
import com.hengxinguotong.zhihuichengjian.widget.view.TopScrollView;
import com.hengxinguotong.zhihuichengjian.widget.waterwave.WaterRippleView;
import com.inpor.fastmeetingcloud.sdk.HstLoginManager;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 项目主页 包含天气
 * Created by Administrator on 2017/10/31.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private View rootView = null;
    private static final String TAG = "HomeFragment";
    @BindView(R.id.pic_bg)
    RelativeLayout picBg;
    @BindView(R.id.home_vp)
    ViewPager homeVp;
    @BindView(R.id.point_container)
    LinearLayout pointContainer;
    @BindView(R.id.weather_bg)
    RelativeLayout weatherBg;
    @BindView(R.id.scan_iv)
    LinearLayout scanIv;
    @BindView(R.id.liebiao)
    ImageView liebiao;
    @BindView(R.id.title_tv)
    HXTextView title_tv;
    @BindView(R.id.top_message_title)
    HXTextView topMessageTitle;
    @BindView(R.id.top_message_time)
    HXTextView topMessageTime;
    @BindView(R.id.bottom_message_title)
    HXTextView bottomMessageTitle;
    @BindView(R.id.bottom_message_time)
    HXTextView bottomMessageTime;
    @BindView(R.id.history_tv)
    HXTextView historyTv;
    @BindView(R.id.message_container)
    LinearLayout messageContainer;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.mTopScrollView)
    TopScrollView mTopScrollView;
    @BindView(R.id.wrv)
    WaterRippleView mWrv;
    @BindView(R.id.tv_progress_text)
    TextView mTvProgressText;
    @BindView(R.id.rl_water_rate)
    RelativeLayout mRlWaterRate;
    @BindView(R.id.tv_start_date)
    TextView mTvStartDate;
    @BindView(R.id.tv_end_date)
    TextView mTvEndDate;
    @BindView(R.id.tv_plan_day)
    TextView mTvPlanDay;
    @BindView(R.id.tv_finish_day)
    TextView mTvFinishDay;
    @BindView(R.id.message_ll)
    LinearLayout mMessageLl;
    @BindView(R.id.menu_gv)
    NoneRollGridView mMenuGv;
    Unbinder unbinder;

    private MyHomeReceiver myHomeReceiver;

    private MenuListRes menuListRes;
    private List<MenuBean> menuList;
    private HomeMenuListAdapter menuListAdapter;
    //轮播图的集合
    private List<NetworkImageView> list;
    private List<String> fileList;
    private HstLoginManager loginManager;
    //轮播图当前页
    private int currentPage = 0;
    private boolean isFirst = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Constants.UPDATE:
                    int type = (int) msg.obj;
                    updateMenuList(type);
                    getMessages(null);
                    break;
            }
        }
    };

    private void updateMenuList(int type) {
        switch (type) {
            case 0:
            case 13:
                for (MenuBean menu : menuList) {
                    menu.setHasNew(false);
                }
                break;
            case 1:
                for (MenuBean menu : menuList) {
                    if (menu.getId() == 300) {
                        menu.setHasNew(true);
                        if (menu.getData() != null && menu.getData().size() > 0) {
                            for (MenuBean smenu : menu.getData()) {
                                if (smenu.getId() == 330) {
                                    smenu.setHasNew(true);
                                }
                            }
                        }
                    }
                }
                break;
            case 2:
                for (MenuBean menu : menuList) {
                    if (menu.getId() == 400) {
                        menu.setHasNew(true);
                        if (menu.getData() != null && menu.getData().size() > 0) {
                            for (MenuBean smenu : menu.getData()) {
                                if (smenu.getId() == 430) {
                                    smenu.setHasNew(true);
                                }
                            }
                        }
                    }
                }
                break;
            case 3:
                for (MenuBean menu : menuList) {
                    if (menu.getId() == 800) {
                        menu.setHasNew(true);
                        if (menu.getData() != null && menu.getData().size() > 0) {
                            for (MenuBean smenu : menu.getData()) {
                                if (smenu.getId() == 810) {
                                    smenu.setHasNew(true);
                                }
                            }
                        }
                    }
                }
                break;
            case 4:
                for (MenuBean menu : menuList) {
                    if (menu.getId() == 800) {
                        menu.setHasNew(true);
                        if (menu.getData() != null && menu.getData().size() > 0) {
                            for (MenuBean smenu : menu.getData()) {
                                if (smenu.getId() == 820) {
                                    smenu.setHasNew(true);
                                }
                            }
                        }
                    }
                }
                break;
            case 5:
                for (MenuBean menu : menuList) {
                    if (menu.getId() == 800) {
                        menu.setHasNew(true);
                        if (menu.getData() != null && menu.getData().size() > 0) {
                            for (MenuBean smenu : menu.getData()) {
                                if (smenu.getId() == 830) {
                                    smenu.setHasNew(true);
                                }
                            }
                        }
                    }
                }
                break;
            case 12:
                for (MenuBean menu : menuList) {
                    if (menu.getId() == 1500) {
                        menu.setHasNew(true);
                        if (menu.getData() != null && menu.getData().size() > 0) {
                            for (MenuBean smenu : menu.getData()) {
                                if (smenu.getId() == 1520) {
                                    smenu.setHasNew(true);
                                }
                            }
                        }
                    }
                }
                break;
        }
        menuListAdapter.setMenuList(menuList);
        MenuListRes res = new MenuListRes();
        res.setValue(menuList);
        String authority = new Gson().toJson(res);
        SPUtil.put(baseActivity, "authority", authority);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, null);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onLazyLoad() {
        getAuthority();
        getHomeInfo("加载中…");
        getMessages(null);
    }

    private void initReceiver() {
        // 1. 实例化BroadcastReceiver子类 &  IntentFilter
        myHomeReceiver = new MyHomeReceiver();
        IntentFilter intentFilter = new IntentFilter();

        // 2. 设置接收广播的类型
        intentFilter.addAction("update_menu");

        // 3. 动态注册：调用Context的registerReceiver（）方法
        getActivity().registerReceiver(myHomeReceiver, intentFilter);
    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);

        //初始化设置为50%
        //设置水波纹进度
        float progress = 0.5f;
        mWrv.setDepthRate(progress);
        mWrv.startRefresh();
        mWrv.startRefresh2();

        if (loginManager == null) {
            loginManager = HstLoginManager.getInstance();
        }
    }

    /**
     * 主页面下拉刷新操作监听
     */
    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener() {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
            getHomeInfo("加载中…");
            getMessages(null);
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

        }
    };

    private void getAuthority() {
        String authority = SPUtil.getString(baseActivity, "authority");
        if (Utils.isEmpty(authority)) {
            getMenuList(SPUtil.getString(baseActivity, "userId"));
        }
        try {
            menuListRes = new Gson().fromJson(authority, MenuListRes.class);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage().toString());
        }
        if (menuListRes == null) {
            Utils.loginOut(baseActivity);
        } else {
            menuList = menuListRes.getValue();
            menuListAdapter = new HomeMenuListAdapter(menuList, baseActivity);
            mMenuGv.setAdapter(menuListAdapter);
            mMenuGv.setOnItemClickListener(this);
            mMenuGv.setFocusable(false);
        }
    }

    /*
     *获取首页菜单权限信息
     */
    private void getMenuList(String userId) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("userId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), baseActivity, "/authority/queryMenuList/" + SPUtil.getString(baseActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                SPUtil.put(baseActivity, "authority", json);
                if (Utils.isEmpty(json)) {
                    Utils.loginOut(baseActivity);
                } else {
                    getAuthority();
                }
            }

            @Override
            public void onFailure(String json) {
                Utils.loginOut(baseActivity);
            }
        });
    }

    public void updateMenu(int type) {//消息类型：0.系统消息； 1.质量整改； 2.安全整改； 3.任务派发； 4.塔吊预约； 5.升降机预约
        android.os.Message msg = handler.obtainMessage();
        msg.what = Constants.UPDATE;
        msg.obj = type;
        msg.sendToTarget();
    }

    private void initView(HomeInfo homeInfo) {
        int level = SPUtil.getInt(baseActivity, "level");
        String title = null;
        switch (level) {
            case 1:
            case 2:
            case 3:
                title = SPUtil.getString(baseActivity, "levelName");
                break;
            default:
                title = SPUtil.getString(baseActivity, "enterpriseName");

                break;
        }
        title_tv.setText(title);
        if (null != homeInfo.getValue().getContractEndDate() && null != homeInfo.getValue().getContractStartDate()) {
//            String end_year = Utils.getYear(homeInfo.getValue().getContractEndDate()) + "";
//            String end_monthAndDay = Utils.getMonthAndDay(homeInfo.getValue().getContractEndDate());
//            endYear.setText(end_year);
//            endDate.setText(end_monthAndDay);
//            String start_year = Utils.getYear(homeInfo.getValue().getContractStartDate()) + "";
//            String start_monthAndDay = Utils.getMonthAndDay(homeInfo.getValue().getContractStartDate());
//            startYear.setText(start_year);
//            startDate.setText(start_monthAndDay);
            String endDate = homeInfo.getValue().getContractEndDate();
            String startDate = homeInfo.getValue().getContractStartDate();
            mTvStartDate.setText(startDate);
            mTvEndDate.setText(endDate);

            int remainderDays = homeInfo.getValue().getRemainderDays();//剩余天数；
            int distanceDay = DateUtil.getDistanceDay(endDate, startDate, DateUtil.DATE_FORMAT_2);
            mTvPlanDay.setText(distanceDay+"日");
            int finishDay = 0;
            if (remainderDays>0){
                finishDay = distanceDay - remainderDays;
            }else {
                finishDay = distanceDay;
            }
            mTvFinishDay.setText(finishDay+"日");
        }
//        if (homeInfo.getValue().getTotalNum() > 0) {
//            localTv.setText(homeInfo.getValue().getLocale() + "");
//            totalTv.setText(homeInfo.getValue().getTotalNum() + "");
//        } else {
//            temperareLl.setVisibility(View.GONE);
//        }

        //设置进度
        //设置水波纹进度
        String projectProgress = homeInfo.getValue().getProjectProgress();
        if(!TextUtils.isEmpty(projectProgress)) {
            String replace = projectProgress.replace("%", "");
            float aFloat = Float.valueOf(replace);
            if (aFloat>100){
                aFloat = 100l;
            }
            //设置显示数字
            mTvProgressText.setText((int)aFloat+"%");
            float progress = aFloat/100;
            mWrv.setDepthRate(progress);
            mWrv.startRefresh();
            mWrv.startRefresh2();
        }

        if (level == 1 || level == 2) {
            liebiao.setVisibility(View.VISIBLE);
        } else {
            liebiao.setVisibility(View.GONE);
        }
        //        int lightBlue = getResources().getColor(R.color.color_lightblue);
        //        int darkBlue =  getResources().getColor(R.color.color_darkblue);
        //        functionModule.setColor(darkBlue, lightBlue);
        //        functionModule.setTypeface(Utils.getTypeface(baseActivity));
        if (null == homeInfo.getValue()) {
            showToast("当前首页信息为空");
            return;
        }
        if (homeInfo.getValue().getFileList() != null && homeInfo.getValue().getFileList().size() > 0) {
            picBg.setVisibility(View.VISIBLE);
            weatherBg.setVisibility(View.GONE);
//            infoLl.setBackgroundResource(R.drawable.home_bg);
            fileList = new ArrayList<String>();
            fileList.addAll(homeInfo.getValue().getFileList());
            initHomeVp();
        } else {
            weatherBg.setVisibility(View.VISIBLE);
            picBg.setVisibility(View.GONE);
            String cityname = homeInfo.getValue().getCityName();
//            if (Utils.isEmpty(cityname))
//                cityname = "武汉市";
//            cityName.setText(cityname);
//            if (null != homeInfo.getValue().getTemperature()) {
//                temperature.setText(homeInfo.getValue().getTemperature() + "°C");
//            } else {
//                temperature.setText("_°C");
//            }
//            switch (homeInfo.getValue().getType()) {
//                case 0:
//                    weatherImg.setImageResource(R.mipmap.qingtian);
//                    break;
//
//                case 1:
//                    weatherImg.setImageResource(R.mipmap.duoyun);
//                    break;
//
//                case 2:
//                    weatherImg.setImageResource(R.mipmap.xiayu);
//                    break;
//
//                case 3:
//                    weatherImg.setImageResource(R.mipmap.xiaxue);
//                    break;
//            }
//            weatherTv.setText(homeInfo.getValue().getWeather());
//            getWeather(cityname);
        }
    }

    //初始化轮播图
    private void initHomeVp() {
        list = new ArrayList<NetworkImageView>();
        for (int i = 0; i < fileList.size(); i++) {
            NetworkImageView iv = new NetworkImageView(baseActivity);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            String url = fileList.get(i);
            //            iv.setImageURL(url);
            Glide.with(getActivity())
                    .load(url)
                    .placeholder(R.mipmap.banner0)
                    .error(R.mipmap.banner0)
                    .into(iv);
            list.add(iv);
        }
        homeVp.setAdapter(new MyVPAdapter());
        homeVp.setCurrentItem(currentPage);
        homeVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                for (int i = 0; i < pointContainer.getChildCount(); i++) {
                    ImageView imageView = (ImageView) pointContainer.getChildAt(i);
                    if (i == position) {
                        imageView.setImageResource(R.mipmap.round);
                    } else {
                        imageView.setImageResource(R.mipmap.round_hui);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (isFirst) {
            initPoints();
            handler.postDelayed(new MyRun(), 3000);
            isFirst = false;
        }
    }

    //初始化轮播图下的小圆点
    private void initPoints() {
        pointContainer.removeAllViews();
        for (int i = 0; i < fileList.size(); i++) {
            ImageView dot = new ImageView(baseActivity);
            if (i == currentPage) {
                dot.setImageResource(R.mipmap.round);
            } else {
                dot.setImageResource(R.mipmap.round_hui);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                    .LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            if (i > 0) {
                params.leftMargin = 10;//设置圆点边距
            }
            dot.setLayoutParams(params);
            pointContainer.addView(dot);
        }
    }

    //每隔2秒调度轮播图一次
    private class MyRun implements Runnable {

        @Override
        public void run() {
            int item = homeVp.getCurrentItem() + 1;
            homeVp.setCurrentItem(item);
            if (item == list.size()) {
                homeVp.setCurrentItem(0);
            }
            handler.postDelayed(new MyRun(), 2000);
        }
    }

    private class MyVPAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(list.get(position));
            return list.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private void processMessage(MessageListRes messageListRes) {
        if (messageListRes.getValue() != null && messageListRes.getValue().size() > 0) {
            messageContainer.setVisibility(View.VISIBLE);
            historyTv.setVisibility(View.GONE);
            List<Message> datas = messageListRes.getValue();
            if (datas.size() < 2) {
                topMessageTitle.setText(datas.get(0).getContent());
                topMessageTime.setText(datas.get(0).getCreateTime());
                bottomMessageTitle.setVisibility(View.INVISIBLE);
                bottomMessageTime.setVisibility(View.INVISIBLE);
            } else {
                topMessageTitle.setText(datas.get(0).getContent());
                topMessageTime.setText(datas.get(0).getCreateTime());
                bottomMessageTitle.setVisibility(View.VISIBLE);
                bottomMessageTime.setVisibility(View.VISIBLE);
                bottomMessageTitle.setText(datas.get(1).getContent());
                bottomMessageTime.setText(datas.get(1).getCreateTime());
            }
        } else {
            messageContainer.setVisibility(View.GONE);
            historyTv.setVisibility(View.VISIBLE);
        }
    }

    private void getMessages(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pageNum", "1");
            jsonObject.put("flag", "1");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/message/query/" + SPUtil.getString(baseActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);

                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    MessageListRes messageListRes = gson.fromJson(json, MessageListRes.class);
                    if (messageListRes.getStatus() == 1) {
                        processMessage(messageListRes);
                    } else {
                        showToast("获取消息失败，请稍后重试！");
                        messageContainer.setVisibility(View.GONE);
                        historyTv.setVisibility(View.VISIBLE);
                    }
                } else {
                    showToast("获取消息失败，请稍后重试！");
                    messageContainer.setVisibility(View.GONE);
                    historyTv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(String json) {
                refreshList.refreshFinish(PullToRefreshLayout.FAIL);

                showToast("获取消息失败，请稍后重试！");
                messageContainer.setVisibility(View.GONE);
                historyTv.setVisibility(View.VISIBLE);
            }
        });
    }

//    private void getWeather(String cityName) {
//        new HttpUtils().send(HttpRequest.HttpMethod.GET, "http://wthrcdn.etouch.cn/weather_mini?city=" + cityName, null,
//                new RequestCallBack<String>() {
//
//                    @Override
//                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        Logger.d("responseInfo.result----" + responseInfo.result);
//                        Gson gson = new Gson();
//                        WeatherRes weatherRes = gson.fromJson(responseInfo.result, WeatherRes.class);
//                        if (null != weatherRes.getData()) {
//                            Weather weather = weatherRes.getData();
//                            if (null != weather.getWendu()) {
//                                temperature.setText(weatherRes.getData().getWendu() + "°C");
//                            } else {
//                                temperature.setText("_°C");
//                            }
//                            if (null != weather.getForecast() && weather.getForecast().size() > 0) {
//                                Weather.Forecast forecast = weather.getForecast().get(0);
//                                weatherTv.setText(forecast.getType());
//                                if (forecast.getType().contains("晴")) {
//                                    weatherImg.setImageResource(R.mipmap.qingtian);
//                                } else if (forecast.getType().contains("阴") || forecast.getType().contains("云")) {
//                                    weatherImg.setImageResource(R.mipmap.duoyun);
//                                } else if (forecast.getType().contains("雨")) {
//                                    weatherImg.setImageResource(R.mipmap.xiayu);
//                                } else if (forecast.getType().contains("雪")) {
//                                    weatherImg.setImageResource(R.mipmap.xiaxue);
//                                } else {
//                                    weatherImg.setImageResource(R.mipmap.qingtian);
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(HttpException error, String msg) {
//                        Log.e(TAG, "error===>>>" + error.toString() + "msg===>>>" + msg);
//                    }
//                });
//    }

    private void getHomeInfo(String alert) {
        String constructionId = SPUtil.getString(baseActivity, "constructionid");
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", constructionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert,baseActivity, "/home/getHomeInfo/" + SPUtil.getString(baseActivity,"uuid"),
                params, new Utils.ListenerJson() {
                    @Override
                    public void onSuccess(String json) {
                        refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);

                        SPUtil.put(baseActivity, "homeinfo", json);
                        Gson gson = new Gson();
                        HomeInfo homeInfo = gson.fromJson(json, HomeInfo.class);
                        if (1 == homeInfo.getStatus()) {
                            initView(homeInfo);
                        } else if (0 == homeInfo.getStatus()) {
                            showToast(homeInfo.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(String json) {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);

                        showToast(json);
                    }
                });
    }

    @OnClick({R.id.scan_iv, R.id.liebiao, R.id.message_ll})
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.scan_iv:
                intent = new Intent(baseActivity, CaptureActivity.class);
                startActivity(intent);
                baseActivity.overridePendingTransition(R.anim.activity_in_from_rigth, R.anim.activity_out_to_scale);
                break;
            case R.id.liebiao:
                intent = new Intent(baseActivity, MainActivity.class);
                startActivity(intent);
                ActivityController.finishAll();
                break;

            case R.id.message_ll:
                intent = new Intent(baseActivity, MessageActivity.class);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MenuBean menuBean = menuList.get(position);
        int menuId = menuBean.getId();
        switch (menuId) {
            case 100://视频监控
            case 700://环境监测
            case 900://文档管理
            case 1000://能耗监测
            case 1100://吊钩监测
            case 1200://统计报表
            case 280://车辆管理
                ActivityJumper.jumpByURL(menuBean, baseActivity);
                break;
            case 0:
            case 50://监督检查
            case 200://人员管理
            case 300://质量管理
            case 400://安全管理
            case 500://设备管理
            case 600://材料管理
            case 800://工程管理
            case 1300://高支模管理
            case 1400:
            case 1500:
            case 1600:
            case 1700:
            case 1800:
            case 1900:
                ActivityJumper.jumpToMenu(menuBean, baseActivity);
                break;
            case 2000:
                //视频会议
                openVedioMeeting();
                break;
        }
    }

    /**
     * 打开视频会议
     */
    private void openVedioMeeting() {
        //获取ip和port
        Utils.requestData(getString(R.string.loading),baseActivity, "/video/getIpAndPort/" + SPUtil.getString(baseActivity,"uuid"),
                null, new Utils.ListenerJson() {
                    @Override
                    public void onSuccess(String json) {
                        refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
                        Gson gson = new Gson();
                        VedioMeetingRst vedioMeetingRst = gson.fromJson(json, VedioMeetingRst.class);
                        if (1 == vedioMeetingRst.getStatus()) {
                            VedioMeetingBean meetingBean = vedioMeetingRst.getValue();
                            //缓存登录信息
                            String jsonStr = gson.toJson(meetingBean);
                            SPUtil.put(getActivity(),Constants.MEETING_INFO,jsonStr);
                            //登录好视通
                            loginHST(meetingBean);
                        } else if (0 == vedioMeetingRst.getStatus()) {
                            getIPFail(vedioMeetingRst.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(String json) {
                        getIPFail(json);
                    }
                });



    }

    /**
     * 获取视频会议地址失败
     * @param msg
     */
    private void getIPFail(String msg){
        String meetingInfo = SPUtil.getString(baseActivity, Constants.MEETING_INFO);
        if (TextUtils.isEmpty(meetingInfo)){
            showToast(msg);
        }else {
            Gson gson = new Gson();
            VedioMeetingBean meetingBean = gson.fromJson(meetingInfo, VedioMeetingBean.class);
            loginHST(meetingBean);
        }
    }

    /**
     * 登录好视通
     * @param meetingBean
     */
    private void loginHST(VedioMeetingBean meetingBean) {
        loginManager.enterRoom(getActivity(),
                meetingBean.getIp(),
                meetingBean.getApp_port()+"",
                SPUtil.getString(baseActivity, "userName")/*"user01"*/,
                Constants.HST_PSD,
                "");
    }

    @Override
    public void onResume() {
        super.onResume();
        initReceiver();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(myHomeReceiver);
        unbinder.unbind();
    }

    private class MyHomeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String authority = SPUtil.getString(baseActivity, "authority");
            if (Utils.isEmpty(authority)) {
                getMenuList(SPUtil.getString(baseActivity, "userId"));
            }
            try {
                menuListRes = new Gson().fromJson(authority, MenuListRes.class);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage().toString());
            }
            menuList = menuListRes.getValue();
            menuListAdapter.setMenuList(menuList);
            getMessages("加载中…");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            String authority = SPUtil.getString(baseActivity, "authority");
            if (Utils.isEmpty(authority)) {
                getMenuList(SPUtil.getString(baseActivity, "userId"));
            }
            try {
                menuListRes = new Gson().fromJson(authority, MenuListRes.class);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage().toString());
            }
            menuList = menuListRes.getValue();
            menuListAdapter.setMenuList(menuList);
            getMessages("加载中…");
        }
    }
}
